package cn.imvc.app.models;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Goods;
import cn.imvc.app.entities.GoodsCountry;
import cn.imvc.app.repositories.GoodsCountryRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;

@Service
public class GoodsCountryModelImpl implements GoodsCountryModel{

	@Autowired
	GoodsCountryRepository goodsCountryRepository;
	
	public Page<GoodsCountry> find(ViewRequest viewRequest) {
		return goodsCountryRepository.findAll(viewRequest);
	}

	public GoodsCountry get(int id) {
		return goodsCountryRepository.getOne(id);
	}

	public int save(GoodsCountry goodsCountry) {
		Goods goods = goodsCountry.getGoods();
		int goodsId = goods.getId();
		List<GoodsCountry> gg = goodsCountryRepository.getByGoodsId(goodsId);
		if(gg.size()>0){
			return 0;
		}
		goodsCountryRepository.saveAndFlush(goodsCountry);
		return 1;
	}

	public int update(int id, GoodsCountry goodsCountry) {
		GoodsCountry loadGoodsCountry = goodsCountryRepository.getOne(id);
		Goods goods = goodsCountry.getGoods();
		int goodsId = goods.getId();
		List<GoodsCountry> gg = goodsCountryRepository.getByGoodsId(goodsId);
		if(gg.size()>0&&!goods.equals(loadGoodsCountry.getGoods())){
			return 0;
		}
		BeanUtils.copyProperties(goodsCountry, loadGoodsCountry, new String[]{"id"});
		goodsCountryRepository.saveAndFlush(goodsCountry);
		return 1;
	}

	public void delete(int id) {
		goodsCountryRepository.delete(id);
	}

}
